package cn.jbit.test.io.bio.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/10
 */
public class BioClient {

    private  static Socket  socket;

    private  static InputStream is;

    private  static OutputStream oos;

    public static void main(String[] args) throws IOException {
         //客户端建立连接
        //socket=new Socket("localhost",8080);

        Scanner  scanner=new Scanner(System.in);

        String input =null;

        //客户端创建链接
        Client  client=new Client(8080,"localhost");

        while ((input=scanner.next()).length()>0){
           String res=client.request(input);
            System.out.println("response："+res);
        }
    }

    static  class  Client{

        int port;

        String host;

        public Client(int port, String host) {
            this.port = port;
            this.host = host;
        }

        public  boolean  connect(){
            if (socket!=null&&is!=null&&oos!=null&&socket.isBound()&&socket.isConnected()&&!socket.isClosed()){
                return  true;
            }
            try {
                socket=new Socket("localhost",8080);
                is=socket.getInputStream();
                oos=socket.getOutputStream();
                return  true;
            }catch (IOException e){
                try {
                    if (socket!=null){
                        socket.close();
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                try {
                    if (is!=null){
                        is.close();
                    }
                }catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                try {
                    if (oos!=null){
                        oos.close();
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
            return  false;
        }

        public String request(String  request) throws IOException {
                if (!connect()){
                    return  null;
                }
                try {
                    oos.write(request.getBytes());
                    int length=0;
                    //将服务器端返回来的消息存在字节数组中
                    byte[] res=new byte[1000];
                    //进行轮询处理
                    while ((length=is.read(res))>0){

                        return  new String(res,0,length);
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
                return null;
        }
    }
}
